import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import ModalPicsComponent from '../../customer-management/enterprise/details/_components/ModalPicsComponent';
import { ScrollView } from 'react-navigation';
import { Switch } from 'react-native-gesture-handler';
import MethodUtil from '../../../utils/MethodUtil';

const scale = GLOBAL.SCALE;
const TAB_LIST = [
	{
		name: '合同内容',
		type: 0, // TODO
	}, {
		name: '申请信息',
		type: 1, // TODO
	}
]
const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}
export class preReviewDetail extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '合同预审',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		let { orderId, itemData } = this.props.navigation.state.params || {}
		this.orderId = orderId
		this.state = {
			status: 'data',
			companyIndex: 0,
			refuseModalVisible: false,
			type: 0,
			res: {
				orderInfo: {
					hisOrderPreAuditInfo: {}
				},
				orderItemList: []
			},
			itemData
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
	}

	async componentWillMount() {
		await this.initPage();
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
		})
		let res = await HTTP.POST(API_GENERATE(API.PRE_TAST_DETAIL), { orderId: this.orderId }); // TODO
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: 'data',
				res
			})
		} else {
			this.setState({
				status: 'error',
			})
		}
	}

	async _getImgPreview(fileId) {
		if (!fileId) {
			return
		}
		else {
			const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
			if (response && response.image && response.image.length) {
				modalPicDelCfg.visible = true;
				modalPicDelCfg.urls[0] = {
					url: response.image,
					width: Dimensions.get('window').width
				};
				modalPicDelCfg.picPress = () => {
					modalPicDelCfg.visible = false;
					modalPicDelCfg.urls = [];
					this.setState({
						previewModalVisible: false,
					});
				}
			}
		}
	}

	// tab切换
	changeTab = (item) => {
		this.setState({
			type: item.type
		})
	}

	_toMoney(num) {
		if (num) {
			num = MethodUtil.toThousands(num || 0, 2)
			return num
		}
		else {
			return 0
		}
	}
	async _audit() {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.PRE_TAST_AUDIT), {
			businessKey: this.businessKey,
			auditResult: this.isAgreed,
			formKey: "PRE_AUDIT",
			remark: this.remark, // 填写
		});
		this.setState({ loaded: false });
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this.timer = setTimeout(() => {
					this.props.navigation.navigate('preReviewList')
					if (this.props.navigation.state.params.callback) {
						this.props.navigation.state.params.callback()
					}
				}, 800)
			})
		} else {
			this.requesting = false;
		}
	}

	_pass() {
		this.isAgreed = 1;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse() {
		this.isAgreed = 0;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	// tab
	_renderTabWrap() {
		const { type } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={styles.tabItem}>
								<Text style={[styles.tabText, type == item.type ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}
	_tradingInformation(name, pre, now) {
		return (
			<View style={styles.contentBox}>
				<View style={styles.contentLeft}>
					<Text style={styles.contentWeight}>
						{name}
					</Text>
				</View>
				<View style={styles.contentCenter}>
					<Text style={styles.contentText}>
						{pre}
					</Text>
				</View>
				<View style={styles.contentRight}>
					<Text style={pre === now ? styles.contentText : styles.contentTextRed}>
						{now}
					</Text>
				</View>

			</View>
		)
	}
	_tradingFlex(name, pre, now) {
		return (
			<View style={styles.contentFlexBox}>
				<View style={styles.contentLeft}>
					<Text style={styles.contentWeight}>
						{name}
					</Text>
				</View>
				<View style={styles.contentHorizontal}>
					<Text style={[styles.contentText, { marginBottom: 10 * scale }]}>
						{pre}
					</Text>
					<Text style={pre === now ? styles.contentText : styles.contentTextRed}>
						{now}
					</Text>
				</View>
			</View>
		)
	}
	_payTypeFilter(payType) {
		switch (payType) {
			case '1':
				return '全额'
			case '2':
				return '定金'
			case '3':
				return '货到'
			case '4':
				return '款到'
			case '5':
				return '见单'
			default:
				return ''
		}
	}
	_renderToastWrap() {
		let { orderInfo, orderItemList } = this.state.res
		let { lostRender, lostRate, freeDays, transportTypeName, logisticsFee, deliveryBeginDate, deliveryEndDate,
			signTime, signAddress, voucherExpireDays, settleDisputesName, payExpireDays, bankName, acctNo, isUniteName,
			payType, remark, deliveryAddress, orderType
		} = orderInfo.hisOrderPreAuditInfo
		let { itemData } = this.state
		return (
			<View style={{ flex: 1 }}>
				{this.state.type == 0 ?
					<View style={{ flex: 1 }}>
						<View style={styles.contentTitle}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentText}>
									字段名称
								</Text>
							</View>
							<View style={styles.contentCenter}>
								<Text style={styles.contentText}>
									业务/基础数据落值
						</Text>
							</View>
							<View style={styles.contentRight}>
								<Text style={styles.contentTextRed}>
									商务落值
						</Text>
							</View>
						</View>
						<ScrollView style={styles.conContent}>
							<Text style={styles.conTitle}>
								交易信息
							</Text>
							{this._tradingInformation('业务类型', isUniteName || '-', orderInfo.isUniteName || '-')}
							{this._tradingInformation('途损承担方', lostRender == 1 ? '我方' : lostRender == 2 ? '对方' : '-', orderInfo.lostRender == 1 ? '我方' : orderInfo.lostRender == 2 ? '对方' : '-')}
							{this._tradingInformation('途损率（‰）', lostRate || lostRate == 0 ? MethodUtil.countObj.multiply(lostRate, 1000).toFixed(4) : '-', orderInfo.lostRate || orderInfo.lostRate == 0 ? MethodUtil.countObj.multiply(orderInfo.lostRate, 1000).toFixed(4) : '-')}
							{this._tradingInformation('免仓期（天）', freeDays || '-', orderInfo.freeDays || '-')}
							{this._tradingInformation('运输方式', transportTypeName || '-', orderInfo.transportTypeName || '-')}
							{this._tradingInformation('运输成本', logisticsFee || logisticsFee == 0 ? this._toMoney(logisticsFee) : '-', orderInfo.logisticsFee || orderInfo.logisticsFee == 0 ? this._toMoney(orderInfo.logisticsFee) : '-')}
							{this._tradingInformation('交货开始日期', deliveryBeginDate ? deliveryBeginDate.substring(0, 10) : '-', orderInfo.deliveryBeginDate ? orderInfo.deliveryBeginDate.substring(0, 10) : '-')}
							{this._tradingInformation('交货结束日期', deliveryEndDate ? deliveryEndDate.substring(0, 10) : '-', orderInfo.deliveryEndDate ? orderInfo.deliveryEndDate.substring(0, 10) : '-')}
							{this._tradingInformation('签约日期', signTime ? signTime.substring(0, 10) : '-', orderInfo.signTime ? orderInfo.signTime.substring(0, 10) : '-')}
							{this._tradingInformation('签约地址', signAddress || '-', orderInfo.signAddress || '-')}
							{this._tradingInformation('发票时限', voucherExpireDays || '-', orderInfo.voucherExpireDays || '-')}
							{this._tradingFlex('合同争议解决', settleDisputesName || '-', orderInfo.settleDisputesName || '-')}
							{this._tradingInformation(orderType === 'S' ? '收款期限（天）' : '付款期限（天）', payType && payExpireDays ? (this._payTypeFilter(payType) + '/' + payExpireDays) : '-', orderInfo.payType && orderInfo.payExpireDays ? (this._payTypeFilter(orderInfo.payType) + '/' + orderInfo.payExpireDays) : '-')}
							{this._tradingFlex(orderType === 'S' ? '收款银行账号' : '付款银行账号', (bankName && acctNo) ? bankName + '/' + acctNo : '-', (orderInfo.bankName && orderInfo.acctNo) ? orderInfo.bankName + '/' + orderInfo.acctNo : '-')}
							{this._tradingFlex('合同地址', deliveryAddress || '-', orderInfo.deliveryAddress || '-')}
							{this._tradingFlex('合同备注', remark || '-', orderInfo.remark || '-')}
							{this._tradingFlex('送审备注', orderInfo.auditRemark || '-', orderInfo.auditRemark || '-')}
							{orderItemList && orderItemList.length > 0 ? orderItemList.map((item, index) => {
								return (
									<View key={index} style={{ marginTop: 20 * scale }}>
										<Text style={styles.conTitle}>
											商品名称：{item.goodsName} ({item.transLevel}级)
										</Text>
										{this._tradingFlex('品质约定', item.hisOrderPreItem && item.hisOrderPreItem.qualityStdName ? item.hisOrderPreItem.qualityStdName : '-', item.qualityStdName || '-')}
										{this._tradingFlex('品质说明', item.hisOrderPreItem && item.hisOrderPreItem.qualityRemark ? item.hisOrderPreItem.qualityRemark : '-', item.qualityRemark || '-')}
										{this._tradingFlex('溢短装率（%）', item.hisOrderPreItem && item.hisOrderPreItem.ysPercent ? item.hisOrderPreItem.ysPercent : '-', item.ysPercent || '-')}
									</View>
								)
							})
								: null
							}
							<View style={{ marginBottom: 50 * scale }}>
							</View>
						</ScrollView>
						<View style={styles.buttonBox}>
							<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
								this.businessKey = this.orderId;
								this._pass();
							}}>
								<Text style={styles.buttonPassText}>同意</Text>
							</TouchableOpacity>
							<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
								this.businessKey = this.orderId;
								this._refuse();
							}}>
								<Text style={styles.buttonRefuseText}>驳回</Text>
							</TouchableOpacity>
						</View>
					</View>
					:
					<View style={styles.applyInfo}>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									订单编号
								</Text>
							</View>
							<View style={[styles.contentHorizontal, { flexDirection: 'row', alignItems: "center" }]}>
								<Text style={styles.contentText}>
									{itemData.orderId || '-'}
								</Text>
								{itemData.orderId ?
									<TouchableOpacity onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId: itemData.orderId }) }}>
										<Text style={[styles.contentText, { color: '#0091FF', marginLeft: 5 * scale }]}>[查看订单]</Text>
									</TouchableOpacity> : null
								}
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									客户名称
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.companyName}
								</Text>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									关联闭口订单号
								</Text>
							</View>
							<View style={[styles.contentHorizontal, { flexDirection: 'row', alignItems: "center" }]}>
								<Text style={styles.contentText}>
									{itemData.oppoOrderId || '-'}
								</Text>
								{itemData.oppoOrderId ?
									<TouchableOpacity onPress={() => { this.props.navigation.navigate('OrderDetailsPage', { orderId: itemData.oppoOrderId }) }}>
										<Text style={[styles.contentText, { color: '#0091FF', marginLeft: 5 * scale }]}>[查看订单]</Text>
									</TouchableOpacity> : null
								}
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									合同标准
								</Text>
							</View>
							<View style={[styles.contentHorizontal, { flexDirection: 'row', alignItems: "center" }]}>
								<Text style={styles.contentText}>
									{itemData.contractStandard == '1' ? '标准合同' : '外部合同'}
								</Text>
								<TouchableOpacity onPress={() => {
									this.props.navigation.navigate('ContractPdfPage', {
										finalFileId: itemData.finalFileId,
										title: '附件信息'
									})
								}}>
									<Text style={[styles.contentText, { color: '#0091FF', marginLeft: 5 * scale }]}>[查看附件]</Text>
								</TouchableOpacity>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									签约日期
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.signTime ? itemData.signTime.substring(0, 10) : '-'}
								</Text>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									业务员
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.bizStaffName}
								</Text>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									订单部门
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.bizTeamName + '/' + itemData.organName}
								</Text>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									制单人
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.documentaryByName || '-'}
								</Text>
							</View>
						</View>
						<View style={styles.applyInfoHorizon}>
							<View style={styles.contentLeft}>
								<Text style={styles.contentWeight}>
									创建时间
								</Text>
							</View>
							<View style={styles.contentHorizontal}>
								<Text style={styles.contentText}>
									{itemData.createTime}
								</Text>
							</View>
						</View>
					</View>
				}
			</View>
		)
	}

	render() {
		let { status } = this.state;
		return (
			<View style={styles.container}>
				{this._renderTabWrap()}
				{this._renderToastWrap()}
				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
				<ModalPicsComponent {...modalPicDelCfg} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	tabWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 10
	},
	tabItem: {
		flex: 1,
		justifyContent: 'center',
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
	},
	tabText: {
		color: '#fff'
	},
	contentLeft: {
		flex: 1,
	},
	contentText: {
		fontSize: 12 * scale,
		color: "#000"
	},
	contentCenter: {
		flex: 1,
		alignItems: 'flex-start'
	},
	contentTextRed: {
		fontSize: 12 * scale,
		color: 'red'
	},
	contentRight: {
		flex: 1,
		alignItems: 'flex-end'
	},
	contentTitle: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingHorizontal: 15 * scale,
		paddingTop: 20 * scale,
		paddingBottom: 10 * scale
	},
	conContent: {
		flex: 1,
		paddingVertical: 20 * scale,
		// paddingHorizontal: 5 * scale,
		backgroundColor: '#fff',
		// paddingBottom: 100 * scale
	},
	conTitle: {
		fontWeight: '600',
		marginBottom: 10 * scale,
		marginLeft: 15 * scale
	},
	contentBox: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingHorizontal: 15 * scale,
		paddingTop: 20 * scale,
		paddingBottom: 10 * scale,
		borderBottomWidth: 2 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#e4e4e4'
	},
	contentWeight: {
		fontSize: 12 * scale,
		color: "#000",
		fontWeight: '600'
	},
	contentHorizontal: {
		flex: 2
	},
	contentFlexBox: {
		flexDirection: 'row',
		alignItems: 'flex-start',
		paddingHorizontal: 15 * scale,
		paddingTop: 20 * scale,
		paddingBottom: 10 * scale,
		borderBottomWidth: 2 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: '#e4e4e4'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginTop: 18 * scale,
		height: 70 * scale
	},
	buttonPass: {
		width: 80 * scale,
		backgroundColor: style.color.themeColor,
		paddingVertical: 10 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 20 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 80 * scale,
		paddingVertical: 10 * scale,
		marginBottom: 12 * scale,
		borderRadius: 20 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	applyInfo: {
		paddingHorizontal: 15 * scale,
		paddingTop: 20 * scale,
		paddingBottom: 10 * scale,
	},
	applyInfoHorizon: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 20 * scale
	},
})